package com.kkb.kkbauth.controller;

import com.kkb.kkbauth.domain.Oauth2AccessTokenDto;
import com.kkb.kkbcommon.api.CommonResult;
import com.kkb.kkbcommon.constant.AuthConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Map;

@Api(value = "Oauth2颁发令牌")
@RestController
@RequestMapping(value = "/auth")
public class Oauth2Controller {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @ApiOperation(value = "", notes = "")
    @GetMapping(value = "/token")
    public CommonResult<Oauth2AccessTokenDto> getOauth2Token(Principal principal, Map<String, String> paramters) throws HttpRequestMethodNotSupportedException {

        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, paramters).getBody();
        Oauth2AccessTokenDto oauth2AccessTokenDto = Oauth2AccessTokenDto.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead(AuthConstant.JWT_TOKEN_PREFIX)
                .build();

        return CommonResult.success(oauth2AccessTokenDto, "成功获取令牌");
    }
}